package tomsung.cloud.agdc.image;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 图片 base64字符串 转化类
 * 
 * @author MiJunQiang
 *
 */
public class ImageBase64Util {

	private static final Logger logger = LoggerFactory.getLogger(ImageBase64Util.class);

	/**
	 * 图片转化成base64字符串
	 * 
	 * @param file
	 * @return base64
	 */
	public static String getImageBase64(String file) {
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(file);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			logger.error("Get base64 from {0} error", file, e);
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);
	}

	/**
	 * 
	 * 实例化图片到文件
	 * 
	 * @param base64
	 * @param file
	 *            文件路径
	 * @return
	 */
	public static boolean instanceImage(String base64, String file) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(base64);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(file);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			logger.error("Instance picture error", e);
			return false;
		}
	}
}
